package com.killer.edu.oauth.oauth2.enhancer;

import com.killer.edu.oauth.entity.UserJwt;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义token携带内容
 */
public class CustomTokenEnhancer implements TokenEnhancer{


    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String,Object> additionalInfo=new HashMap<String,Object>();
        //自定义token内容，加入组织结构信息
        additionalInfo.put("organization", authentication.getName());
        try {
            //自定义token内容,加入userId
            UserJwt details=(UserJwt)authentication.getPrincipal();
            if (details != null) {
                additionalInfo.put("user_id", details.getId());
            }
            ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(additionalInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
